package com.turing.manage.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;


@SuppressWarnings("serial")
public class ManagerServlet extends HttpServlet {
	
	ManagerService managerService = new ManagerService();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			String method = request.getParameter("method");
			
			if ("query".equals(method)) 
			{
				this.query(request,response);
			}
			else if ("addPage".equals(method))
			{
				this.addPage(request,response);
			}
			else if ("add".equals(method)) 
			{
				this.add(request, response);
			}
			else if ("download".equals(method)) 
			{
				this.download(request,response);
			}
			else if ("editPage".equals(method)) 
			{
				this.editPage(request,response);
			}
			else if ("edit".equals(method)) 
			{
				this.edit(request,response);
			}
			else if ("delete".equals(method)) 
			{
				this.delete(request,response);
			}
		} catch (Exception e) {
			System.out.println("1.发送的异常信息为:"+e.getMessage());
			System.out.println("2.发送异常的内存地址为:"+e.getStackTrace());
			System.out.println("3.转向到错误处理页面");
			request.setAttribute("errorMsg",e.getMessage());
			request.getRequestDispatcher("/manage/error.jsp").forward(request, response);
		}
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, SQLException {
		
		//1.接值：要删除的这条数据的主键
		String id = request.getParameter("manager_id");
		
		//2.调用service中的方法删除这条数据
		managerService.deleteByld(id);
		
		//3.重定向
		response.sendRedirect(request.getContextPath()+"/manage/manager.do?method=query");
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, SQLException, FileUploadException {
		
				//0.设定类型和编码
				response.setContentType("text/html;charset=utf-8");
				//1.定义变量
				String fileSavaName = null;//文件保存的名字
				List<FileItem> formFileItemList ;
				//2.设定图片保存在服务器上的路径
				String path = this.getServletContext().getRealPath("/")+"WEB-INF/image";
				System.out.println("图片存储路径:"+path);
				//3.根据图片保存的路径进行一下创建
				File file = new File(path);
				if (!file.exists()) {
					file.mkdir();
				}
				//4.利用commons-fileupload.jar实现上传
				DiskFileItemFactory factory = new DiskFileItemFactory();
				//5.加载文件上传解析器
				ServletFileUpload upload = new ServletFileUpload(factory);
				//6.设置解析器的一些参数值
				upload.setHeaderEncoding("utf-8");
				//upload.setSizeMax(1024*10);//设置大小为10kb
				//7.解析上传的图片
				formFileItemList = upload.parseRequest(request);
				if (formFileItemList!=null&&formFileItemList.size()>0)
				{
					for (FileItem everyFileItem : formFileItemList) {
						if (!everyFileItem.isFormField()) {
							String fileName = everyFileItem.getName();//获取本次上传的文件的名字
							System.out.println("上传的文件的名字为:"+fileName);
							//获取上传的图片的后缀
							String prefix = fileName.substring(fileName.lastIndexOf(".")+1);
							System.out.println("后缀为:"+prefix);
							//通过UUID获取一个不重复的最终的文件的名字
							fileSavaName = UUID.randomUUID().toString()+"."+prefix;
							System.out.println("文件最终保存的名字为:"+fileSavaName);
							//利用commoms-io.jar包中的方法就可以实现文件上传
							FileUtils.copyInputStreamToFile(everyFileItem.getInputStream(), new File(path+"/"+fileSavaName));
						}
					}
				}
				//8.获取添加页面上的其他数据
				String manager_id = formFileItemList.get(0).getString("utf-8");
				String manager_name = formFileItemList.get(1).getString("utf-8");
				String manager_pass = formFileItemList.get(2).getString("utf-8");
		    
		   managerService.updateStudent(manager_id,manager_name,manager_pass,fileSavaName);
		    
		    //3.重定向
		    response.sendRedirect(request.getContextPath()+"/manage/manager.do?method=query");
	}

	private void editPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException {
		String id = request.getParameter("manager_id");
		Map<String, Object> map = managerService.querymanagerById(id);
		request.setAttribute("map", map);
		request.getRequestDispatcher("/manage/manager/edit.jsp").forward(request, response);
	}

	private void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//1.接值
		String manager_imgpath = request.getParameter("manager_imgpath");
		System.out.println("manager_imgpath--->"+manager_imgpath);
		
		try {
			String path = this.getServletContext().getRealPath("/")+"WEB-INF/image/";
			File file = new File(path+manager_imgpath);
			FileInputStream fileInputStream = new FileInputStream(file);
			response.setContentType("image/jpg");//设置返回的文件类型
			response.setHeader("Access-Control-Allow-Origin", "*");//设置该图片允许跨域访问
			IOUtils.copy(fileInputStream, response.getOutputStream());
		} catch (Exception e) {
			String path = this.getServletContext().getRealPath("/") + "WEB-INF/image/默认.png";
			File  fileLocal=new File(path);
			FileInputStream fileInputStream=new FileInputStream(fileLocal);
			System.out.println("图片没找到。。。。。");
			response.setContentType("image/jpg"); //设置返回的文件类型   
			response.setHeader("Access-Control-Allow-Origin", "*");
			IOUtils.copy(fileInputStream, response.getOutputStream());
			//this.downloadOutSider(request, response);
		}
	}
	
	/**
	* @desc  4.下载照片(利用外链)	
	* @param request
	* @param response
	* @throws IOException 
	*/
//	private void downloadOutSider(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		
//		String imgUrl="https://www.baidu.com/img/bd_logo1.png";
//		URL url = new URL(imgUrl);                 
//		URLConnection conn = url.openConnection();  
//		InputStream inStream = conn.getInputStream();        
//		response.setContentType("image/jpg"); //设置返回的文件类型   
//		response.setHeader("Access-Control-Allow-Origin", "*");//设置该图片允许跨域访问
//		IOUtils.copy(inStream, response.getOutputStream()); 
//	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException, ClassNotFoundException, SQLException {
		System.out.println("upload()--->");
		//0.设定类型和编码
		response.setContentType("text/html;charset=utf-8");
		//1.定义变量
		String fileSavaName = null;//文件保存的名字
		List<FileItem> formFileItemList ;
		//2.设定图片保存在服务器上的路径
		String path = this.getServletContext().getRealPath("/")+"WEB-INF/image";
		System.out.println("图片存储路径:"+path);
		//3.根据图片保存的路径进行一下创建
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		//4.利用commons-fileupload.jar实现上传
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//5.加载文件上传解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		//6.设置解析器的一些参数值
		upload.setHeaderEncoding("utf-8");
		//upload.setSizeMax(1024*10);//设置大小为10kb
		//7.解析上传的图片
		formFileItemList = upload.parseRequest(request);
		if (formFileItemList!=null&&formFileItemList.size()>0)
		{
			for (FileItem everyFileItem : formFileItemList) {
				if (!everyFileItem.isFormField()) {
					String fileName = everyFileItem.getName();//获取本次上传的文件的名字
					System.out.println("上传的文件的名字为:"+fileName);
					//获取上传的图片的后缀
					String prefix = fileName.substring(fileName.lastIndexOf(".")+1);
					System.out.println("后缀为:"+prefix);
					//通过UUID获取一个不重复的最终的文件的名字
					fileSavaName = UUID.randomUUID().toString()+"."+prefix;
					System.out.println("文件最终保存的名字为:"+fileSavaName);
					//利用commoms-io.jar包中的方法就可以实现文件上传
					FileUtils.copyInputStreamToFile(everyFileItem.getInputStream(), new File(path+"/"+fileSavaName));
				}
			}
		}
		//8.获取添加页面上的其他数据
		String manager_name = formFileItemList.get(0).getString("utf-8");
		String manager_pass = formFileItemList.get(1).getString("utf-8");
		String virtulpath = fileSavaName;
		System.out.println(manager_name+"\t"+manager_pass);
		//9.调用M层保存本次添加页面的数据
		managerService.save(manager_name,manager_pass,virtulpath);
		//10重定向
		response.sendRedirect(request.getContextPath()+"/manage/manager.do?method=query");
		
	}

	private void addPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.getRequestDispatcher("/manage/manager/add.jsp").forward(request, response);
	}

	private void query(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException  {
		
		List<Map<String,Object>> list = managerService.queryManagerAll();
		
		request.setAttribute("list",list);
		
		request.getRequestDispatcher("/manage/manager/list.jsp").forward(request, response);
	}	
}
